<?php
  session_start();
  define('SITE_PATH','http://localhost/nb158jk/mysql_new');
  date_default_timezone_set('Asia/Kolkata');

  $isPrint = true;
  $arrLog = array();
  // true => want to print
  // false => don't want to print

  $userName = 'root';
  $password = '';
  $host = 'localhost';
  $dbName = 'nb158jk';

  #connect to MYSQL
  mysql_connect($host, $userName, $password) or die(mysql_error());
  # Select Database
  mysql_select_db($dbName) or die(mysql_error());


  #Mysql Functions
  function pr($arr = array())
  {
    global $isPrint;
    global $arrLog;
    if($isPrint == false)
    return false;

    $log =  '<pre style="color:#fff;background-color:#000;padding:10px;border-radius:10px;box-shadow:10px 10px 10px gray;">';
    $log .= print_r($arr,1);
    $log .= '</pre>';
    $arrLog[] = $log;
  }


  function pq($arr = array())
  {
    global $isPrint;
    global $arrLog;
    if($isPrint == false)
    return false;

    $log = '<div style="color:red;background-color:yellow;padding:10px;border-radius:10px;box-shadow:10px 10px 10px gray;">';
    $log .= print_r($arr,1);
    $log .= '</div>';
    $arrLog[] = $log;
  }


  function getStatus($status=0)
  {
    return $status==0 ? 'Inactive':'Active';
  }


   ################### Database functions ################################

  /*
   * Used to fetch Data from DB table
   * @param $tableName STRING e.g. "users"
   * @param $where STRING e.g. "post LIKE '%php%'"
   * @param $fields STRING e.g. "id,name,link,head"
   * @param $order STRING e.g. "aded_date DESC"
   * @param $limit STRING e.g. "0,10"
   *
   * @return RESOURCE
   * */
  function fetchAll($tableName='',$where='',$fields='',$order='',$limit='')
  {
    if($tableName=='') {
      return false;
    }

    $where = $where!='' ? " WHERE $where" :'';
    $fields = $fields!='' ? $fields :'*';
    $order = $order!='' ? "ORDER BY $order" :'';
    $limit = $limit!='' ? "LIMIT $limit" :'';

    $totalQuery = "SELECT $fields FROM `$tableName` $where $order $limit";
    $totalResult = dbQuery($totalQuery);

    return $totalResult;
  }

  /*
   * Used to Update Data in DB table
   * @param $tableName STRING e.g. "users"
   * @param $where STRING e.g. "post LIKE '%php%'"
   * @param $data ARRAY e.g. "array('name'=>'php','title'=>'First Post')"
   *
   * @return Number of updated rows
   * */
  function update($tableName='',$where='',$data=array())
  {
    if($tableName==''||$where=='') {
      return false;
    }
      $tmp = '';
      foreach($data as $colName=>$value) {
        $tmp .= "`$colName`='$value' ,";
      }
      $tmp = rtrim($tmp, ' ,');

    $query = "UPDATE `$tableName` SET $tmp WHERE $where";
    dbQuery($query);
    return mysql_affected_rows();
  }

  /*
   * Used to Count number of records in DB table
   * @param $tableName STRING e.g. "users"
   * @param $where STRING e.g. "post LIKE '%php%'"
   * @return INT total number of records found
   * */
  function countAll($tableName='',$where='')
  {
    if($tableName=='') {
      return false;
    }
    $where = $where!='' ? " WHERE $where" :'';

    $totalQuery = "SELECT COUNT(*) as `total` FROM `$tableName` $where";

    $totalResult = dbQuery($totalQuery);
    $totalAns = mysql_fetch_assoc($totalResult);
    return $totalAns['total'];
  }


  /*
   * DELETE records FROM DB table
   * @param $tableName STRING e.g. "users"
   * @param $where STRING e.g. "id = '2'"
   * @return INT total number of deleted rows
   * */
  function delete($tableName='', $where='')
  {
    if($tableName==''||$where=='') {
      return false;
    }
    $where = $where!='' ? "WHERE $where" :'';
    $query = "DELETE FROM `$tableName`
              $where";
    dbQuery($query);
    return mysql_affected_rows();
  }


  /*
   * Replacement of mysql_query() function
   * used to maintain logs
   * */
  function dbQuery($query='')
  {
    global $logArr;
    $result = mysql_query($query) or die(mysql_error());

    $traceArray = (array_reverse(debug_backtrace()));
    $file =$traceArray[0]['file'];
    $line = $traceArray[0]['line'];
    $logArr[] = "$file on Line $line";
    pq($query);
    return $result;
  }

  /*
   * Used to insert Data in Database table
   * @param $tableName STRING e.g. "users"
   * @param $data ARRAY e.g. "array('..'=>'..',....)"
   * @return INT INSERT ID
   * */
  function dbInsert($tableName='',$fields=array())
  {
    if($tableName==''|| empty($fields)) {
      return false;
    }
    $fields = array_map('arrayCleanup',$fields);

      $query = "INSERT INTO `$tableName` SET ";
      $tmp = '';
      foreach($fields as $colName=>$value) {
        $value =
        $tmp .= "`$colName`='$value' ,";
      }
      $tmp = rtrim($tmp, ' ,');
      $query = $query.$tmp;
      dbQuery($query);
      return mysql_insert_id();
  }

  /*
   * Used to call from array_map() as callback
   * to prevent Sql injection though $_POST (associative array)
   *
   * @param  : $str STRING
   * @param  : $tagsAllowed BOOL i.e if false then strip tags
   * @return : Clean Array
   *
   * Usage : $_POST = array_map('arrayCleanup',$_POST);
   * */
  function arrayCleanup($str, $tagsAllowed = false){
    return $tagsAllowed == true ? mysql_real_escape_string(trim($str))
                                : strip_tags(mysql_real_escape_string(trim($str)));
  }
